package cn.wuxing.mediation.web.controller.util;

import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.json.JSONUtil;
import cn.wuxing.mediation.common.core.domain.entity.SysDept;
import cn.wuxing.mediation.common.core.domain.entity.SysUser;
import cn.wuxing.mediation.common.utils.SecurityUtils;
import cn.wuxing.mediation.system.mapper.SysDeptMapper;
import cn.wuxing.mediation.system.mapper.SysUserMapper;
import cn.wuxing.mediation.system.service.ISysDeptService;
import cn.wuxing.mediation.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DataProcessor {

    // 批量处理大小
    private static final int BATCH_SIZE = 500;

    // 假设有服务类或DAO进行数据库操作
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysDeptService sysDeptService;
    private static List<SysDept> sysDepts = new ArrayList<>();
    private static List<SysUser> sysUsers = new ArrayList<>();


    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysDeptMapper sysDeptMapper;

    @Value("${zzd.password}")
    private String password;

    //发送消息 浙政钉消息
    public void sendNews() {

    }

    /*// 主处理方法
    public void processOrganizationsAndEmployees(List<Organization> organizations, List<Employee> employees) {
        // 转换并处理组织数据

        organizations.stream()
                .forEach(this::convertToSysDept);
        batchProcessDepts(sysDepts);

        // 转换并处理员工数据
        employees.stream()
                .forEach(this::convertToSysUser);
        batchProcessUsers(sysUsers);
    }
*/
    public void addEmployees(List<Employee> employees) {
        // 转换并处理员工数据
        List<SysUser> collect = employees.stream()
                .map(this::convertToSysUser).collect(Collectors.toList());

    }

    public void addOrganizations(List<Organization> organizations) {
        List<SysDept> collect = organizations.stream()
                .map(this::convertToSysDept).collect(Collectors.toList());

    }

    // 将 Employee 转换为 SysUser
    private SysUser convertToSysUser(Employee employee) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(StringToLongIdGenerator.generateId(employee.getEmployeeCode().replace("GE_", ""))); // 假设转换逻辑
        String pinyin = PinyinUtil.getPinyin(employee.getEmployeeName(),"");
        int count = sysUserMapper.selectCountLikeUserName(pinyin);
        // 生成唯一的用户名
        String userNameWithSuffix = pinyin;

        if (count > 0) {
            // 如果拼音已经存在，添加后缀编号
            userNameWithSuffix = pinyin + String.format("%02d", count + 1);
        }
        sysUser.setUserName(userNameWithSuffix);
        sysUser.setNickName(employee.getEmployeeName());
        sysUser.setStatus("A".equals(employee.getStatus()) ? "0" : "1"); // 状态转换：A=正常，F=停用
        sysUser.setSex("M".equals(employee.getEmpGender()) ? "0" : "1"); // 示例性别转换
//        sysUser.setEmail(employee.getEmployeeExtProperties().getOrDefault("email", ""));
//        sysUser.setPhonenumber(employee.getAccount());
//        sysUser.setPhonenumber(employee.getEmployeeExtProperties().getOrDefault("phone", ""));
        sysUser.setDeptId(employee.getDeptId());
        sysUser.setAccountId(employee.getAccountId());
        sysUser.setEmployeeCode(employee.getEmployeeCode());
        sysUser.setPassword(SecurityUtils.encryptPassword(password));

        log.info("即将存入数据库的用户信息是：{}", JSONUtil.toJsonStr(sysUser));
        int saveOrUpdateBatch = 0;
        boolean flag = sysUserService.selectUserById(sysUser.getUserId()) == null ? true : false;
        if (flag) {
            saveOrUpdateBatch = sysUserMapper.insertUser(sysUser);
        } else {
            sysUser.setUserName(null);
            sysUser.setPassword(null);
            saveOrUpdateBatch = sysUserMapper.updateUser(sysUser);
        }
        log.info("存入数据库结果是：{}", saveOrUpdateBatch);
        //TODO 其他字段映射...
        return sysUser;
    }

    // 将 Organization 转换为 SysDept
    private SysDept convertToSysDept(Organization org) {
        SysDept sysDept = new SysDept();
        sysDept.setDeptId(StringToLongIdGenerator.generateId(org.getOrganizationCode())); // 假设转换逻辑
        sysDept.setDeptName(org.getOrganizationName());
        //TODO 换成吴兴区code
        if (org.getParentCode().equals("GO_33fae8273a344e508ebf272a58987c53")) {
            sysDept.setParentId(100L);
        } else {
            sysDept.setParentId(StringToLongIdGenerator.generateId(org.getParentCode()));
        }
        sysDept.setLeader(org.getContactEmployeeCode());
        sysDept.setPhone(org.getContactNumber());
        sysDept.setEmail(org.getUnifiedSocialCreditCode()); // 示例映射
        sysDept.setStatus("A".equals(org.getStatus()) ? "0" : "1"); // 状态转换
        sysDept.setOrganizationCode(org.getOrganizationCode());
        sysDept.setOrderNum(org.getDisplayOrder());
        sysDept.setAncestors(assemblerAncestors(org.getParentCode()));
        log.info("即将存入数据库的组织信息是：{}", JSONUtil.toJsonStr(sysDept));
        int saveOrUpdateBatch = 0;
        boolean flag = sysDeptService.selectDeptById(sysDept.getDeptId()) == null ? true : false;
        if (flag) {
            saveOrUpdateBatch = sysDeptMapper.insertDept(sysDept);
        } else {
            saveOrUpdateBatch = sysDeptMapper.updateDept(sysDept);
        }
        log.info("存入数据库结果是：{}", saveOrUpdateBatch);
        //TODO 其他字段映射...
        return sysDept;
    }

    public String assemblerAncestors(String deptCode) {
        StringBuilder ancestors = new StringBuilder();
        Long deptId = StringToLongIdGenerator.generateId(deptCode);
        do {
            SysDept sysDept = sysDeptService.selectDeptById(deptId);
            if (sysDept != null) {
                if (sysDept.getDeptId() == 0L) {
                    ancestors.insert(0, "0,100,");
                } else {
                    ancestors.insert(0, sysDept.getDeptId() + ",");
                    deptId = sysDept.getParentId();
                }
            } else {
                deptId = 0L;
                ancestors.insert(0, "0,100,");
            }
        } while (deptId != 0L);
        return ancestors.toString().endsWith(",") ? ancestors.substring(0, ancestors.toString().length() - 1) : ancestors.toString();
    }

    //    // 批量处理组织数据
//    private void batchProcessDepts(List<SysDept> sysDepts) {
//        for (int i = 0; i < sysDepts.size(); i += BATCH_SIZE) {
//            List<SysDept> batch = sysDepts.subList(i, Math.min(i + BATCH_SIZE, sysDepts.size()));
//            sysDeptService.saveOrUpdateBatch(batch);
//        }
//    }
//
//    // 批量处理用户数据
//    private void batchProcessUsers(List<SysUser> sysUsers) {
//        for (int i = 0; i < sysUsers.size(); i += BATCH_SIZE) {
//            List<SysUser> batch = sysUsers.subList(i, Math.min(i + BATCH_SIZE, sysUsers.size()));
//            sysUserService.saveOrUpdateBatch(batch);
//        }
//    }


    public static void main(String[] args) {
        System.out.println(PinyinUtil.getPinyin("陈苏民",""));
    }
}
